#!/usr/bin/perl
use strict;
my $file = $ARGV[0];
open BUFF, "<$file" or die "can't open the $file\n";
open FIN,"/data1/bsi/bioinf_int/s106381.borawork/Chien_data/samplebam/samtools-0.1.12a/samtools-0.1.12a/samtools pileup -l $file $ARGV[1] 2>/dev/null |  " or die "not able to open $file and $ARGV[1] using pileup\n";
#open FIN,"/data1/bsi/bioinf_int/s106381.borawork/Chien_data/samplebam/samtools-0.1.12a/samtools-0.1.12a/samtools pileup $ARGV[1] 2>/dev/null |  " or die "not able to open $file and $ARGV[1] using pileup\n";
#open FIN,"/data1/bsi/bioinf_int/s106381.borawork/Chien_data/samplebam/samtools-0.1.12a/samtools-0.1.12a/samtools pileup -l $file $ARGV[1] |  " or die "not able to open $file and $ARGV[1] using pileup\n";


my $line = <BUFF> or die "No positions to read\n";
$line =~ /^(chr[0-9,X,Y]+) ([0-9]+)/;
my $chr = $1;
my $chrnum=23;
my $pos = $2;
if(!($chr eq "chrX")) {$chr =~ /chr([0-9]+)/;$chrnum=$1;}
#print "$chrnum $pos\n";
if(! (-d "temp")) {
    system("mkdir temp");
}
my $outfile = "./temp/out_fast";
open(FTEMP,">$outfile");
my $l;
while($l = <FIN>)
{
	my @data = split("\t",$l);
	my $bchr = $data[0];
	my $bchrnum = 23;
	if(!($bchr eq "chrX")) 
	{
	    $bchr =~ /chr([0-9]+)/;
	    $bchrnum=$1;
	}
	my $bpos = $data[1];
	while($chrnum<$bchrnum  || ($chrnum==$bchrnum && $bpos>$pos)) 
	{
		#print "success\n";
		#print FTEMP "$chr $pos 0 0 0 0\n";
		print FTEMP "NA\n";
		if($line = <BUFF>) 
		{
			$line =~ /^(chr[0-9,X,Y]+) ([0-9]+)/;
			$chr = $1;
			$pos = $2;
			$chrnum=23;
			if(!($chr eq "chrX")) 
			{
		    		$chr =~ /chr([0-9]+)/;
		    		$chrnum=$1;
			}
	    	}	 
		else 
		{
			 close FTEMP;
		 	close FIN; 
		 	exit 0 ;
	     	}
	}
	#print "$bpos\t$pos\t$bchrnum\t$chrnum\n";
	if(($bpos==$pos) && ($bchrnum == $chrnum)) 
	{
		$data[4] =~ tr/acgt/ACGT/;
	    	my @count=(0,0,0,0);
	    	my $cigar = $data[4];
	    	$count[0] =  () = $cigar =~ /A/g;
	    	$count[1] =  () = $cigar =~ /C/g;
	    	$count[2] =  () = $cigar =~ /G/g;
	    	$count[3] =  () = $cigar =~ /T/g;	

	    	#print FTEMP "$chr $pos " . join("_",@count) ."\n";
	    	print FTEMP join("_",@count) ."\n";
		if($line = <BUFF>) 
		{
			$line =~ /^(chr[X,Y,0-9]+) ([0-9]+)/;
			$chr = $1;
			$chrnum=23;
			$pos = $2;
			if(!($chr eq "chrX")) 
			{
		    		$chr =~ /chr([0-9]+)/;
		    		$chrnum=$1;
			}
	    	}	 
		else 
		{
			close FTEMP;
			close FIN;
			exit 0;
	    	}
	}
}
close FIN;
#print FTEMP "$chr $pos 0 0 0 0\n";
print FTEMP "NA\n";
while($line=<BUFF>) 
{
    $line =~ s/[\r,\l,\n,\t]+$//;
    $line =~ /^(chr[X,Y,0-9]+) ([0-9]+)/;
    $line =~ s/[\r,\l,\n,\t]+$//g;
    #print FTEMP "$line 0 0 0 0\n";
	print FTEMP "NA\n";
}
close FTEMP;
close BUFF;
